#include "25aa1024.h"

/*
	read

	This function takes in pointers to the starting address and data arrays,
	as well as the amount of data (in bytes) to be read.
*/

void read(uint8_t *data, int amount, uint8_t *address)
{
	//Pull CS low to select device
	ss_lo();

	//Send READ instruction
	spi_master_init();
	spi_tx(_READ);

	//Send address to be read
	for(uint8_t i = 0; i < 3; ++i) {
		spi_tx(address[i]);
	}
	
	//For each byte of data needed
	for(int j = 0; j < amount; ++j) {
		//Send a blank byte, read the data received
		data[j] = spi_tx(0x00);
	}

	//Put CS back high
	ss_hi();
}

/*
	write

	This function takes in pointers to the starting address and data arrays,
	as well as the amount of data (in bytes) to be written. It is only
	capable of writing up to 256 bytes or one page of the memory per call.
*/

void write(uint8_t *data, uint8_t amount, uint8_t *address)
{
	//Pull CS low to select device
	ss_lo();
	
	//Set write enable latch
	spi_master_init();
	spi_tx(_WREN);
	ss_hi();

	//Pull CS low to select device
	ss_lo();

	//Send WRITE instruction
	spi_tx(_WRITE);

	//Send address to be written
	for(uint8_t i = 0; i < 3; ++i) {
		spi_tx(address[i]);
	}

	//Send data to be written (up to 
	//256 bytes)
	for(uint8_t i = 0; i < amount; ++i) {
		spi_tx(data[i]);
	}

	//Write Cycle
	//Bring CS high
	ss_hi();
	//Wait for at least 6ms...10 here to be safe
	_delay_ms(10);	
}
